package com.cs.common.xml;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.cs.common.plugin.InitPlugIn;

/**
 * For parse xml to java clases
 * @version 1.0 
 * @date  2008-10-15
 * @author jdelgado
 */

public class XMLBaseDAO {
	/**
	 * Parse xml to a java classes
	 * @param xmlConfig xml config
	 * @param xmlRules xml rules for parse
	 * @param objectParsed Object to parse
	 * @throws IOException The files need to open
	 * @throws SAXException The xmls needs to be parse
	 */
	public static void parse(String xmlConfig, String xmlRules, Object objectParsed ) throws IOException, SAXException{
		URL url = null;
		StringBuffer buffer = null;
		BufferedReader reader = null;
		String line = null;
		InputSource source = null;
		Digester digester = null;
		InputStream input = null;
		
		buffer = new StringBuffer(0);
		//url = objectParsed.getClass().getResource(xmlRules);
		
		url = new URL(InitPlugIn.LOCALPATH + xmlRules);
		
		input = url.openStream();
		reader = new BufferedReader(new InputStreamReader(input));
		while ( null != (line = reader.readLine())) {
			buffer.append(line);
		}
		source = new InputSource(new StringReader(buffer.toString()));
		digester = DigesterLoader.createDigester(source);
		digester.push( objectParsed );
		
		
		//url = objectParsed.getClass().getResource(xmlConfig);
		url = new URL(InitPlugIn.LOCALPATH + xmlConfig);
		
		input = url.openStream();
		digester.parse( input );
	}
	
	public Object parseTotalStockOutputBean(String xmlConfig, String completeName) throws IOException, SAXException{
		Object object = null;
		BufferedReader reader = null;
		Digester digester = null;
		try {
			digester = new Digester();
			digester.addObjectCreate("ZMM_GET_TOTAL_STOCK/OUTPUT", completeName);
			digester.addCallMethod("ZMM_GET_TOTAL_STOCK/OUTPUT/E_AMOUNT","setE_AMOUNT",0);
			object = digester.parse(new StringReader(xmlConfig.toString()));
		} catch (FileNotFoundException fileNotFoundException) {
			fileNotFoundException.printStackTrace();
		} catch(IOException iOException){
			iOException.printStackTrace();
		}catch(SAXException sAXException){
			sAXException.printStackTrace();
		}catch(Exception exception){
			exception.printStackTrace();
		}finally{
			if (reader != null) {
				try {
					reader.close();
				}catch (IOException iOException){
					iOException.printStackTrace();
				}
			}
		}
		return object;
	}
}
